package com.coolingme.web.pay.alipay;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import lombok.extern.slf4j.Slf4j;
import com.coolingme.properties.DefaultAlipayProperties;

/**
 * 获取支付宝AlipayClient对象<br>
 * alipayClient只需要初始化一次，后续调用不同的API都可以使用同一个alipayClient对象<br>
 * 采用懒汉式单例模式，双重锁
 * 
 * @author: 王越
 * @date: 2019-06-20 21:34:10
 */
@Slf4j
public class DefaultAlipayClientFactory {

	// 私有化构造函数
	private DefaultAlipayClientFactory() {
	}

	// 私有化实例对象，指令重排序volatile
	private volatile static AlipayClient alipayClient = null;

	/**
	 * 返回AlipayClient对象
	 * 
	 * @return AlipayClient
	 */
	public static AlipayClient getAlipayClient() {
		// 第一个检查锁，对象不为空直接返回已有的实例对象
		if (alipayClient == null) {
			// 使用同步锁。若两个线程同时到此处，就会创建两个对象
			synchronized (AlipayClient.class) {
				// 第二个检查锁，再次判断
				if (alipayClient == null) {
					alipayClient = new DefaultAlipayClient(DefaultAlipayProperties.URL, DefaultAlipayProperties.APP_ID,
							DefaultAlipayProperties.RSA_PRIVATE_KEY, DefaultAlipayProperties.FORMAT, DefaultAlipayProperties.CHARSET,
							DefaultAlipayProperties.ALIPAY_PUBLIC_KEY, DefaultAlipayProperties.SIGN_TYPE);
				}
			}
		}
//		log.info("支付宝客户端:" + alipayClient);
		return alipayClient;
	}
}